import { useEffect } from 'react';
import useGameStore from '../context/gameStore';

const useKeyboardInput = () => {
  const handleKeyPress = useGameStore(state => state.handleKeyPress);
  const gameStatus = useGameStore(state => state.gameStatus);

  useEffect(() => {
    if (gameStatus !== 'playing') return;

    const validKeys = ['q', 'w', 'e', 'r', ' '];
    
    const handleKeyDown = (event) => {
      const key = event.key.toLowerCase();
      
      if (validKeys.includes(key)) {
        // 阻止默认行为，防止空格键滚动页面等
        event.preventDefault();
        
        // 处理按键（空格键转换为'space'）
        handleKeyPress(key === ' ' ? 'space' : key, true);
      }
    };
    
    const handleKeyUp = (event) => {
      const key = event.key.toLowerCase();
      
      if (validKeys.includes(key)) {
        event.preventDefault();
        handleKeyPress(key === ' ' ? 'space' : key, false);
      }
    };
    
    // 添加事件监听器
    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);
    
    // 清理函数
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, [handleKeyPress, gameStatus]);
};

export default useKeyboardInput; 